using Godot;
using System;
using System.Collections.Generic;
using TopDownGodot.Src.Globals.Multiplayer;

namespace TopDownGodot.Src.Player;
public partial class Player : CharacterBody2D
{
    [Export]
    public int Speed = 200;

    private bool isAttack = false;

    // 节点引用
    private AnimatedSprite2D PlayerAnimatedSprite => GetNode<AnimatedSprite2D>("PlayerAnimatedSprite");
    private Node2D Eyes => GetNode<Node2D>("Eyes");
    private Camera2D Camera => GetNode<Camera2D>("Camera2D");

    public override void _Ready()
    {
        PlayerAnimatedSprite.Play("D_Idle");
        Eyes.Position = Vector2.Down;

        // 只为当前操控角色的玩家设置摄像机
        if (IsMultiplayerAuthority())
            Camera.MakeCurrent();
    }

    public override void _EnterTree()
    {
        if (MultiplayerGlobal.IsMultiplayer)
            // 设置控制权
            SetMultiplayerAuthority(int.Parse(Name));
    }

    public override void _PhysicsProcess(double delta)
    {
        if (!IsMultiplayerAuthority())
            return;

        Vector2 inputVector = Input.GetVector("player_left", "player_right", "player_up", "player_down");
        Velocity = inputVector * Speed;
        MoveAndSlide();

        // 移动动画
        if (!isAttack)
            UpdateAnimationRun(inputVector);

        Vector2 attackVector = Input.GetVector("attack_left", "attack_right", "attack_up", "attack_down");
        // 攻击动画
        UpdateAnimationAttack(attackVector);
    }

    private void UpdateAnimationRun(Vector2 inputVector)
    {
        // 定义移动时的动画数据
        var moveAnimations = new Dictionary<Vector2, (string animation, bool flip, Vector2 eyesPosition)>
        {
            { Vector2.Left,  ("S_Walk", false, Vector2.Left) },
            { Vector2.Right, ("S_Walk", true,  Vector2.Right) },
            { Vector2.Up,    ("U_Walk", false, Vector2.Up) },
            { Vector2.Down,  ("D_Walk", false, Vector2.Down) }
        };

        // 定义静止时的动画数据（基于眼睛当前朝向）
        var idleAnimations = new Dictionary<Vector2, object>
        {
            { Vector2.Left,  new { animation = "S_Idle", flip = false } },
            { Vector2.Right, new { animation = "S_Idle", flip = true } },
            { Vector2.Up,    "U_Idle" },
            { Vector2.Down,  "D_Idle" }
        };

        // 处理移动逻辑
        if (inputVector.Length() > 0)
        {
            var norm = inputVector.Normalized();
            foreach (var kvp in moveAnimations)
            {
                if (norm == kvp.Key)
                {
                    PlayerAnimatedSprite.Play(kvp.Value.animation);
                    PlayerAnimatedSprite.FlipH = kvp.Value.flip;
                    Eyes.Position = kvp.Value.eyesPosition;
                    return;
                }
            }
        }
        // 处理静止逻辑
        else
        {
            if (idleAnimations.TryGetValue(Eyes.Position, out var idleData))
            {
                if (idleData is string idleAnim)
                {
                    PlayerAnimatedSprite.Play(idleAnim);
                }
                else // S_Idle 左右方向
                {
                    dynamic data = idleData;
                    PlayerAnimatedSprite.Play(data.animation);
                    PlayerAnimatedSprite.FlipH = data.flip;
                }
            }
        }
    }

    private void UpdateAnimationAttack(Vector2 attackVector)
    {
        var attackAnimations = new Dictionary<Vector2, (string animation, bool flip, Vector2 eyesPosition)>
        {
            { Vector2.Left,  ("S_Attack", false, Vector2.Left) },
            { Vector2.Right, ("S_Attack", true,  Vector2.Right) },
            { Vector2.Up,    ("U_Attack", false, Vector2.Up) },
            { Vector2.Down,  ("D_Attack", false, Vector2.Down) }
        };

        if (attackVector.Length() > 0)
        {
            isAttack = true;
            var closestDirection = GetClosestCardinalDirection(attackVector);
            if (attackAnimations.TryGetValue(closestDirection, out var attackData))
            {
                PlayerAnimatedSprite.Play(attackData.animation);
                PlayerAnimatedSprite.FlipH = attackData.flip;
                Eyes.Position = attackData.eyesPosition;
            }
        }
    }

    // 辅助函数：将任意方向向量转换为最近的4个基本方向之一
    private Vector2 GetClosestCardinalDirection(Vector2 direction)
    {
        var normalized = direction.Normalized();
        Vector2[] directions = { Vector2.Left, Vector2.Right, Vector2.Up, Vector2.Down };
        Vector2 closestDir = Vector2.Zero;
        float maxDot = -1f;

        foreach (var dir in directions)
        {
            float dot = normalized.Dot(dir);
            if (dot > maxDot)
            {
                maxDot = dot;
                closestDir = dir;
            }
        }
        return closestDir;
    }

    // 当前动画结束信号
    private void OnPlayerAnimatedSpriteAnimationFinished()
    {
        var animationName = PlayerAnimatedSprite.Animation.ToString().ToLower();
        if (animationName.Contains("attack"))
            isAttack = false;
    }

    //private void OnPlayerAnimatedSpriteFrameChanged()
    //{
    //    // 保留空实现
    //}

    // 需要在 Godot 编辑器里将 PlayerAnimatedSprite 的 AnimationFinished 和 FrameChanged 信号
    // 分别连接到 OnPlayerAnimatedSpriteAnimationFinished 和 OnPlayerAnimatedSpriteFrameChanged 方法
}
